﻿using System;
using System.ServiceModel.Description;
using System.ServiceModel.Dispatcher;
using GianosNET.Common.ClientUtils;
using GianosNET.Common.ServerUtils;

namespace GianosNET.Common.CommonUtils
{
    /// <summary>
    /// This custom behaviour class is used to add both client and server inspectors 
    /// to the corresponding WCF end points.
    /// </summary>
    [AttributeUsage(AttributeTargets.Class)]
    public class CustomBehavior : Attribute, IEndpointBehavior
    {
        #region IEndpointBehavior Members

        public void AddBindingParameters(ServiceEndpoint endpoint, System.ServiceModel.Channels.BindingParameterCollection bindingParameters)
        {
        }

        public void ApplyClientBehavior(ServiceEndpoint endpoint, ClientRuntime clientRuntime)
        {
            ClientMessageInspector inspector = new ClientMessageInspector();
            clientRuntime.MessageInspectors.Add(inspector);
        }

        public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)
        {
            ChannelDispatcher channelDispatcher = endpointDispatcher.ChannelDispatcher;
            if (channelDispatcher != null)
            {
                foreach (EndpointDispatcher ed in channelDispatcher.Endpoints)
                {
                    ed.DispatchRuntime.AutomaticInputSessionShutdown = false;
                    ServerMessageInspector inspector = new ServerMessageInspector();
                    ed.DispatchRuntime.MessageInspectors.Add(inspector);
                    
                }
            }
        }

        public void Validate(ServiceEndpoint endpoint) { }

        #endregion
    } 
}
